import logging
import math
from datetime import datetime
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.engine import create
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

material_cabinet_router = APIRouter(prefix="/material/tsCabinet", tags=["储物柜管理"],
                                    dependencies=[Depends(oauth2_scheme)])


class StorageCabinetSearch(PaginationBase):
    # 筛选条件
    fsiteNo: Optional[str] = Field("", description="站点编号")
    fequipmentbarcode: Optional[str] = Field("", description="设备条码（支持前缀匹配）")
    fstorageflag: Optional[str] = Field("", description="存储标志编码")
    fstate: Optional[str] = Field("", description="状态编码")
    fstockno: Optional[str] = Field("", description="仓库编号")
    fpointNo: Optional[str] = Field("", description="点位编号")
    fmacno: Optional[str] = Field("", description="MAC地址（支持前缀匹配）")


@material_cabinet_router.get("/list", summary="储物柜资料查询接口")
def list_material_cabinet(search: StorageCabinetSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from lims.i_ts_cabinet where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fequipmentbarcode != "":
        sql = sql + " and fequipmentbarcode like concat('%', :fequipmentbarcode ,'%')"
        param["fequipmentbarcode"] = search.fequipmentbarcode
    if search.fmacno != "":
        sql = sql + " and fmacno like concat('%', :fmacno ,'%')"
        param["fmacno"] = search.fmacno
    if search.fstockno != "":
        sql = sql + " and fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fpointNo != "":
        sql = sql + " and fpoint_no = :fpointNo "
        param["fpointNo"] = search.fpointNo
    if search.fstorageflag != "":
        sql = sql + " and fstorageflag = :fstorageflag "
        param["fstorageflag"] = search.fstorageflag
    if search.fstate != "":
        sql = sql + " and fstate = :fstate "
        param["fstate"] = search.fstate
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fequipmentbarcode,feuipmentid,fequipmenttag,fstorageflag,fsite_no,fimage,"
    sql = sql + " fip,fport,flamp1,flamp2,fvideourl,fstockno,flabeltype,fstate,fupddate,"
    sql = sql + " foperator,fmacno,fpoint_no,fpoint_size,flamp3,fdangecabinet"
    sql = sql + " from lims.i_ts_cabinet where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fequipmentbarcode != "":
        sql = sql + " and fequipmentbarcode like concat('%', :fequipmentbarcode ,'%')"
        param["fequipmentbarcode"] = search.fequipmentbarcode
    if search.fmacno != "":
        sql = sql + " and fmacno like concat('%', :fmacno ,'%')"
        param["fmacno"] = search.fmacno
    if search.fstockno != "":
        sql = sql + " and fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fpointNo != "":
        sql = sql + " and fpoint_no = :fpointNo "
        param["fpointNo"] = search.fpointNo
    if search.fstorageflag != "":
        sql = sql + " and fstorageflag = :fstorageflag "
        param["fstorageflag"] = search.fstorageflag
    if search.fstate != "":
        sql = sql + " and fstate = :fstate "
        param["fstate"] = search.fstate
    if search.order == "desc":
        sql = sql + " order by  fpoint_no,fequipmentbarcode desc "
    else:
        sql = sql + " order by  fpoint_no,fequipmentbarcode "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    # details 明细列表
    param = {}
    sql_3 = " select b.fequipmentbarcode,b.fboxbarcode,b.fseq,b.fupddate,b.foperator,c.fequipmenttag"
    sql_3 = sql_3 + " from lims.i_ts_cabinet a,lims.i_ts_cabbox b,lims.i_ts_warehouse c  "
    sql_3 = sql_3 + " where a.fequipmentbarcode=b.fequipmentbarcode"
    sql_3 = sql_3 + " and b.fboxbarcode=c.fequipmentbarcode"
    if search.fsiteNo != "":
        sql_3 = sql_3 + " and a.fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fequipmentbarcode != "":
        sql_3 = sql_3 + " and a.fequipmentbarcode like concat('%', :fequipmentbarcode ,'%')"
        param["fequipmentbarcode"] = search.fequipmentbarcode
    if search.fmacno != "":
        sql_3 = sql_3 + " and a.fmacno like concat('%', :fmacno ,'%')"
        param["fmacno"] = search.fmacno
    if search.fstockno != "":
        sql_3 = sql_3 + " and a.fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fpointNo != "":
        sql_3 = sql_3 + " and a.fpoint_no = :fpointNo "
        param["fpointNo"] = search.fpointNo
    if search.fstorageflag != "":
        sql_3 = sql_3 + " and a.fstorageflag = :fstorageflag "
        param["fstorageflag"] = search.fstorageflag
    if search.fstate != "":
        sql_3 = sql_3 + " and a.fstate = :fstate "
        param["fstate"] = search.fstate
    sql_3 = sql_3 + " order by b.fequipmentbarcode,b.fseq"
    data_detail = db.execute(text(sql_3), param).fetchall()

    data_list = []
    for key in range(len(data)):
        fupddate = ""
        try:
            fupddate = data[key][14].strftime('%Y-%m-%dT%H:%M:%S')
        except Exception as e:
            print(e)

        if (fupddate == ""):
            fupddate = None

        d1 = {}
        d1['fequipmentbarcode'] = data[key][0]
        d1['feuipmentid'] = data[key][1]
        d1['fequipmenttag'] = data[key][2]
        d1['fstorageflag'] = data[key][3]
        d1['fsiteNo'] = data[key][4]
        d1['fimage'] = data[key][5]
        d1['fip'] = data[key][6]
        d1['fport'] = data[key][7]
        d1['flamp1'] = data[key][8]
        d1['flamp2'] = data[key][9]
        d1['fvideourl'] = data[key][10]
        d1['fstockno'] = data[key][11]
        d1['flabeltype'] = data[key][12]
        d1['fstate'] = data[key][13]
        d1['fupddate'] = fupddate
        d1['foperator'] = data[key][15]
        d1['fmacno'] = data[key][16]
        d1['fpointNo'] = data[key][17]
        d1['fpointSize'] = data[key][18]
        d1['flamp3'] = data[key][19]
        d1['fdangecabinet'] = data[key][20]
        detail_list2 = []
        d1["detail_list2"] = detail_list2

        sbillno = data[key][0]

        detail_list = []
        for j1 in range(len(data_detail)):
            if (str(data_detail[j1][0]) == str(sbillno)):
                fupddate = ""
                try:
                    fupddate = data_detail[j1][3].strftime('%Y-%m-%dT%H:%M:%S')
                except Exception as e:
                    print(e)

                if (fupddate == ""):
                    fupddate = None

                d2 = {}
                d2['fequipmentbarcode'] = data_detail[j1][0]
                d2['fboxbarcode'] = data_detail[j1][1]
                d2['fseq'] = data_detail[j1][2]
                d2['fupddate'] = fupddate
                d2['foperator'] = data_detail[j1][4]
                d2['fequipmenttag'] = data_detail[j1][5]
                detail_list.append(d2)

        d1["details"] = detail_list
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class StorageCabinetBoxDetail(BaseModel):
    """储物柜箱子明细"""
    fboxbarcode: str = Field(..., description="箱子条码")


class StorageCabinetCreate(BaseModel):
    """储物柜新增请求参数"""
    fequipmentbarcode: str = Field(..., description="储物柜条码（唯一标识）")
    feuipmentid: str = Field("0", description="设备ID")
    fequipmenttag: str = Field("", description="设备标签")
    fstorageflag: str = Field("", description="存储标志编码")
    fsiteNo: str = Field("", description="站点编号")
    fimage: str = Field("", description="图片路径")
    fip: str = Field("", description="IP地址")
    fport: str = Field("", description="端口号")
    flamp1: str = Field("", description="指示灯1状态")
    flamp2: str = Field("", description="指示灯2状态")
    flamp3: str = Field("", description="指示灯3状态")
    fvideourl: str = Field("", description="视频URL")
    fstockno: str = Field("", description="仓库编号")
    flabeltype: str = Field("0", description="标签类型编码")
    fstate: str = Field("0", description="设备状态编码")
    fmacno: str = Field("", description="MAC地址")
    fpointNo: str = Field("", description="点位编号")
    fpointSize: str = Field("", description="点位尺寸")
    fdangecabinet: str = Field("0", description="危险柜标志")
    frfidtype: str = Field("0", description="RFID类型编码")
    details: List[StorageCabinetBoxDetail] = Field(..., description="箱子明细列表")


@material_cabinet_router.post("/create", summary="储物柜新增接口")
def create_material_cabinet(create: StorageCabinetCreate, db: Session = Depends(get_db),
                            token: str = Depends(oauth2_scheme)):
    try:
        userid = EncryptionMiddleware.get_current_user(token)
        fseq = 0
        fequipmentbarcode = create.fequipmentbarcode
        # 返回内容
        d1 = {}
        now = datetime.now()
        java_time_format_str = now.strftime('%Y-%m-%dT%H:%M:%S')
        detail_list = []
        with db.begin():
            details = create.details
            for detail in details:
                sql = "insert into lims.i_ts_cabbox(fequipmentbarcode,fboxbarcode,fseq,fupddate,foperator)"
                sql = sql + " values( :fequipmentbarcode , :fboxbarcode , :fseq ,now(), :userid );"
                db.execute(text(sql), {
                    "fequipmentbarcode": fequipmentbarcode,
                    "fboxbarcode": detail.fboxbarcode,
                    "fseq": fseq,
                    "userid": userid,
                })
                # 返回明细
                d2 = {}
                d2['fequipmentbarcode'] = fequipmentbarcode
                d2['fboxbarcode'] = detail.fboxbarcode
                d2['fseq'] = fseq
                d2['fupddate'] = java_time_format_str
                d2['foperator'] = userid
                detail_list.append(d2)
                fseq = fseq + 1
            sql = "insert into lims.i_ts_cabinet(fequipmentbarcode,feuipmentid,fequipmenttag,fstorageflag,fsite_no,"
            sql = sql + "fimage,fip,fport,flamp1,flamp2,"
            sql = sql + "fvideourl,fstockno,flabeltype,fstate,fupddate,"
            sql = sql + "foperator,fmacno,fpoint_no,fpoint_size,flamp3,"
            sql = sql + "fdangecabinet,frfidtype)"
            sql = sql + " values( :fequipmentbarcode , :feuipmentid , :fequipmenttag , :fstorageflag , :fsiteNo "
            sql = sql + ", :fimage , :fip , :fport , :flamp1 , :flamp2 "
            sql = sql + ", :fvideourl , :fstockno , :flabeltype , :fstate ,now()"
            sql = sql + ", :userid , :fmacno , :fpointNo , :fpointSize , :flamp3 "
            sql = sql + ", :fdangecabinet , :frfidtype )"
            db.execute(text(sql), {
                "fequipmentbarcode": fequipmentbarcode,
                "feuipmentid": create.feuipmentid,
                "fequipmenttag": create.fequipmenttag,
                "fstorageflag": create.fstorageflag,
                "fsiteNo": create.fsiteNo,
                "fimage": create.fimage,
                "fip": create.fip,
                "fport": create.fport,
                "flamp1": create.flamp1,
                "flamp2": create.flamp2,
                "fvideourl": create.fvideourl,
                "fstockno": create.fstockno,
                "flabeltype": create.flabeltype,
                "fstate": create.fstate,
                "userid": userid,
                "fmacno": create.fmacno,
                "fpointNo": create.fpointNo,
                "fpointSize": create.fpointSize,
                "flamp3": create.flamp3,
                "fdangecabinet": create.fdangecabinet,
                "frfidtype": create.frfidtype,
            })
            d1['fequipmentbarcode'] = fequipmentbarcode
            d1['feuipmentid'] = create.feuipmentid
            d1['fequipmenttag'] = create.fequipmenttag
            d1['fstorageflag'] = create.fstorageflag
            d1['fsiteNo'] = create.fsiteNo
            d1['fimage'] = create.fimage
            d1['fip'] = create.fip
            d1['fport'] = create.fport
            d1['flamp1'] = create.flamp1
            d1['flamp2'] = create.flamp2
            d1['fvideourl'] = create.fvideourl
            d1['fstockno'] = create.fstockno
            d1['flabeltype'] = create.flabeltype
            d1['fstate'] = create.fstate
            d1['fupddate'] = java_time_format_str
            d1['fmacno'] = create.fmacno
            d1['fpointNo'] = create.fpointNo
            d1['fpointsize'] = create.fpointSize
            d1['flamp3'] = create.flamp3
            d1['fdangecabinet'] = create.fdangecabinet
            d1['frfidtype'] = create.frfidtype
            d1["details"] = detail_list
            details2 = []
            d1["details2"] = details2
            return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@material_cabinet_router.post("/update", summary="储物柜修改接口")
def update_material_cabinet(update: StorageCabinetCreate, db: Session = Depends(get_db),
                            token: str = Depends(oauth2_scheme)):
    try:
        userid = EncryptionMiddleware.get_current_user(token)
        fseq = 0
        fequipmentbarcode = update.fequipmentbarcode
        with db.begin():
            sql = "delete from lims.i_ts_cabbox where fequipmentbarcode= :fequipmentbarcode "
            db.execute(text(sql), {
                "fequipmentbarcode": fequipmentbarcode,
            })
            details = update.details
            for detail in details:
                sql = "insert into lims.i_ts_cabbox(fequipmentbarcode,fboxbarcode,fseq,fupddate,foperator)"
                sql = sql + " values( :fequipmentbarcode , :fboxbarcode , :fseq ,now(), :userid );"
                fseq = fseq + 1
                db.execute(text(sql), {
                    "fequipmentbarcode": fequipmentbarcode,
                    "fboxbarcode": detail.fboxbarcode,
                    "fseq": fseq,
                    "userid": userid,
                })
            sql = "update lims.i_ts_cabinet "
            sql = sql + " set fequipmenttag= :fequipmenttag ,fstorageflag= :fstorageflag ,fimage= :fimage "
            sql = sql + ",fip= :fip ,fport= :fport ,flamp1= :flamp1 ,flamp2= :flamp2 "
            sql = sql + ",fvideourl= :fvideourl ,fstockno= :fstockno ,flabeltype= :flabeltype "
            sql = sql + ",fstate= :fstate ,fupddate=now(),foperator= :userid "
            sql = sql + ",fmacno= :fmacno ,fpoint_no= :fpointNo ,fpoint_size= :fpointSize "
            sql = sql + ",flamp3= :flamp3 ,fdangecabinet= :fdangecabinet ,frfidtype= :frfidtype "
            sql = sql + " where fequipmentbarcode= :fequipmentbarcode  and fsite_no= :fsiteNo "
            db.execute(text(sql), {
                "fequipmenttag": update.fequipmenttag,
                "fstorageflag": update.fstorageflag,
                "fimage": update.fimage,
                "fip": update.fip,
                "fport": update.fport,
                "flamp1": update.flamp1,
                "flamp2": update.flamp2,
                "fvideourl": update.fvideourl,
                "fstockno": update.fstockno,
                "flabeltype": update.flabeltype,
                "fstate": update.fstate,
                "userid": userid,
                "fmacno": update.fmacno,
                "fpointNo": update.fpointNo,
                "fpointSize": update.fpointSize,
                "flamp3": update.flamp3,
                "fdangecabinet": update.fdangecabinet,
                "frfidtype": update.frfidtype,
                "fequipmentbarcode": update.fequipmentbarcode,
                "fsiteNo": update.fsiteNo,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@material_cabinet_router.post("/delete/{fequipmentbarcode}", summary="储物柜删除接口")
def delete_material_cabinet(fequipmentbarcode: str = Path(description="设备码"), db: Session = Depends(get_db)):
    try:
        param = {"fequipmentbarcode": fequipmentbarcode}
        with db.begin():
            sql = "select count(1) from i_ts_controlbox where fcatbarcode= :fequipmentbarcode "
            data = db.execute(text(sql), param).fetchall()
            if data[0][0] > 0:
                return BaseResponse.error(message="该资料在使用，不能删除")
            else:
                sql = "delete from lims.i_ts_cabbox where fequipmentbarcode= :fequipmentbarcode "
                db.execute(text(sql), param)
                sql = "delete from lims.i_ts_cabinet where fequipmentbarcode= :fequipmentbarcode "
                db.execute(text(sql), param)
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
